package com.bilibili.xzz.controller;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.bilibili.xzz.entity.User;
import com.bilibili.xzz.service.UserService;
import com.bilibili.xzz.utils.JWTUtil;
import com.bilibili.xzz.utils.Result;
import com.bilibili.xzz.utils.SmsUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;


@RestController
@RequestMapping("/api/login")
public class LoginController {

    @Resource
    UserService userService;

    @PostMapping("/user")
    public Result login(@RequestParam String name,
                        @RequestParam String password) throws Exception {
        User user = userService.getUserByNameAndPwd(name, password);
        if (ObjectUtil.isNotNull(user)) {
            return Result.ok().data("user",user).data("token", JWTUtil.createToken(user.getId()));
        }
        return Result.error().data("errMsg", "用户名或密码错误");
    }

    @PostMapping("/sms")
    public Result getSms(@RequestParam String phone) {
        int[] ints = NumberUtil.generateRandomNumber(100000, 999999, 1);
        String msg = SmsUtil.sendSms(phone, String.valueOf(ints[0]), "10");
        return Result.ok().data("msg", msg);
    }
}
